<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="initImage">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="名称"></el-input>
    </el-form-item>
    <el-form-item label="图标" prop="image">
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :on-error="handleError">
        <img v-if="image" :src="image" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="排序值" prop="sort">
      <el-input-number v-model="dataForm.sort"  :min="0" :max="100000" label="排序值，越小越靠前"></el-input-number>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-switch v-model="dataForm.status" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        uploadUrl:'',
        image: '',
        visible: false,
        dataForm: {
          id: 0,
          name: '',
          image: '',
          sort: '',
          status: '1'
        },
        dataRule: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          image: [
            { required: true, message: '图标不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序值不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.uploadUrl=this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`);
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/forum/tabbar/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.tabbar.name
                this.dataForm.image = data.tabbar.image
                this.dataForm.sort = data.tabbar.sort
                this.dataForm.status = data.tabbar.status
                this.dataForm.createTime = data.tabbar.createTime
                this.dataForm.updateTime = data.tabbar.updateTime
                this.dataForm.deleted = data.tabbar.deleted
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/forum/tabbar/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'image': this.dataForm.image,
                'sort': this.dataForm.sort,
                'status': this.dataForm.status,
                'createTime': this.dataForm.createTime,
                'updateTime': this.dataForm.updateTime,
                'deleted': this.dataForm.deleted
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      //图片上传请求成功后的回调
      handleSuccess(res, file) {
        if(res.code==0){
          this.image = URL.createObjectURL(file.raw);
          this.dataForm.image=res.url
        }else{
          this.$message.error('上传失败，请重新上传！')
        }
      },
      //图片上传请求失败后的回调
      handleError(err, file, fileList){
        this.$message.error('上传失败，请重新上传！')
      },
      //选择文件后触发的回调，可用于检验文件是否符合要求
      beforeUpload(file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        return true;
      },
      //弹窗关闭后，初始化image属性,不清空image下次打开弹窗会继续显示图片
      initImage(){
        this.image='';
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>

